package com.bite.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @RequestMapping("/get")
    public void getCaptcha(HttpServletResponse response, HttpSession session) {
        ICaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100);
        try {
            captcha.write(response.getOutputStream());
            //禁止缓存
            response.setHeader("Prama","No-cache");
            //设置返回格式
            response.setContentType("image/jpeg");
            //打印验证码
            System.out.println(captcha.getCode());
            session.setAttribute("CODE",captcha.getCode());
            session.setAttribute("DATA",System.currentTimeMillis());
            //关闭
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @RequestMapping("/check")
    public boolean check(String captchaCode,HttpSession session) {
        if(!StringUtils.hasLength(captchaCode)) {
            return false;
        }
        String sessionCode = (String) session.getAttribute("CODE");
        Long sessionData = (Long)  session.getAttribute("DATA");
        if(captchaCode.equalsIgnoreCase(sessionCode)
                && sessionData!=null
                && (sessionData-System.currentTimeMillis())<60000) {
            return  true;
        }
        return  false;

    }


}
